package com.tianji.learning.service.impl;

import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tianji.api.client.remark.RemarkClient;
import com.tianji.api.client.user.UserClient;
import com.tianji.api.dto.user.UserDTO;
import com.tianji.common.domain.dto.PageDTO;
import com.tianji.common.exceptions.BizIllegalException;
import com.tianji.common.utils.BeanUtils;
import com.tianji.common.utils.CollUtils;
import com.tianji.common.utils.UserContext;
import com.tianji.learning.domain.dto.ReplyDTO;
import com.tianji.learning.domain.po.InteractionQuestion;
import com.tianji.learning.domain.po.InteractionReply;
import com.tianji.learning.domain.query.ReplyPageQuery;
import com.tianji.learning.domain.vo.ReplyVO;
import com.tianji.learning.enums.QuestionStatus;
import com.tianji.learning.mapper.InteractionQuestionMapper;
import com.tianji.learning.mapper.InteractionReplyMapper;
import com.tianji.learning.service.IInteractionQuestionService;
import com.tianji.learning.service.IInteractionReplyService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.function.Predicate;
import java.util.stream.Collectors;

import static com.tianji.common.constants.Constant.DATA_FIELD_NAME_CREATE_TIME;
import static com.tianji.common.constants.Constant.DATA_FIELD_NAME_LIKED_TIME;

/**
 * <p>
 * 互动问题的回答或评论 服务实现类
 * </p>
 *
 * @author zzj
 * @since 2024-05-05
 */
@Service
@RequiredArgsConstructor
public class InteractionReplyServiceImpl extends ServiceImpl<InteractionReplyMapper, InteractionReply> implements IInteractionReplyService {

    private final InteractionQuestionMapper questionMapper;
    private final UserClient userClient;
    private final RemarkClient remarkClient;

    @Override
    public void saveReply(ReplyDTO dto) {
        //获取当前登录用户
        Long userId = UserContext.getUser();

        //保存回答或者评论  interaction_reply
        InteractionReply reply = BeanUtils.copyBean(dto, InteractionReply.class);
        reply.setUserId(userId);
        this.save(reply);

        //获取问题实体
        InteractionQuestion question = questionMapper.selectById(dto.getQuestionId());

        //判断是否是回答 dto.answerId  为空则是回答
        if (dto.getAnswerId() != null) {
            //如果不是回答 累加回答下的评论次数
            InteractionReply replyDB = this.getById(dto.getAnswerId());//回答
            replyDB.setReplyTimes(replyDB.getReplyTimes() + 1);//评论次数累加
            this.updateById(replyDB);
        }else {
            //如果是回答 修改问题表最近一次回答的id 同时累加回答表回答次数
            question.setLatestAnswerId(reply.getId());
            question.setAnswerTimes(question.getAnswerTimes() + 1);
        }

        //判断是否是学生提交 dto.isStudent为true则代表学生提交 如果是则将问题表的status改为未查看
        if (dto.getIsStudent()) {
            question.setStatus(QuestionStatus.UN_CHECK);
        }
        questionMapper.updateById(question);

    }

    @Override
    public PageDTO<ReplyVO> queryReplyVoPage(ReplyPageQuery query) {
        //检验
        if (query.getQuestionId() == null && query.getAnswerId() == null) {
            throw new BizIllegalException("查询参数错误");
        }
        Page<InteractionReply> page = this.lambdaQuery()
                .eq(query.getQuestionId() != null, InteractionReply::getQuestionId, query.getQuestionId())
//                .eq(query.getAnswerId() != null, InteractionReply::getAnswerId, query.getAnswerId())
                //如果回答id没传，则查询answer_id为0的数量，也就是问答
                .eq(InteractionReply::getAnswerId,query.getAnswerId() == null ? 0L : query.getAnswerId())
                .eq(InteractionReply::getHidden, false)
                .page(query.toMpPage(
                        new OrderItem(DATA_FIELD_NAME_LIKED_TIME,false),
                        new OrderItem(DATA_FIELD_NAME_CREATE_TIME,false)
                ));
        List<InteractionReply> records = page.getRecords();
        if (CollUtils.isEmpty(records)) {
            return PageDTO.empty(0L,0L);
        }

        //远程调用用户服务 ，获取用户信息
        Set<Long> userIds = new HashSet<>();
        List<Long> answerIds = new ArrayList<>();
//        Set<Long> targetReplyIds = new HashSet<>();
        for (InteractionReply record : records) {
            if (!record.getAnonymity()){
                userIds.add(record.getUserId());
                userIds.add(record.getTargetUserId());
            }
            answerIds.add(record.getId());
//            if (record.getTargetReplyId() != null && record.getTargetReplyId() > 0){
//                targetReplyIds.add(record.getTargetReplyId());
//            }
        }
//        //查询目标回复，如果目标回复不是匿名，则需要查询出目标回复的用户信息
//        if (targetReplyIds.size() > 0){
//            List<InteractionReply> targetReplies = listByIds(targetReplyIds);
//            Set<Long> targetUserIds = targetReplies.stream()
//                    .filter(Predicate.not(InteractionReply::getAnonymity))
//                    .map(InteractionReply::getUserId)
//                    .collect(Collectors.toSet());
//            userIds.addAll(targetUserIds);
//        }
        List<UserDTO> userDTOS = userClient.queryUserByIds(userIds);
        Map<Long, UserDTO> userDTOMap = userDTOS.stream().collect(Collectors.toMap(UserDTO::getId, c -> c));

        //查询用户点赞状态
        Set<Long> likesStatusByBizIds = remarkClient.getLikesStatusByBizIds(answerIds);

        //封装vo返回
        List<ReplyVO> voList = new ArrayList<>();
        for (InteractionReply record : records) {
            ReplyVO vo = BeanUtils.copyBean(record, ReplyVO.class);
            if (!vo.getAnonymity()) {
                UserDTO userDTO = userDTOMap.get(record.getUserId());
                if (userDTO != null) {
                    vo.setUserName(userDTO.getName());
                    vo.setUserIcon(userDTO.getIcon());
                }
            }
            UserDTO targetUserDTO = userDTOMap.get(record.getTargetUserId());
            if (targetUserDTO != null){
                vo.setTargetUserName(targetUserDTO.getName());
            }
            //点赞状态
            vo.setLiked(likesStatusByBizIds.contains(record.getId()));
            voList.add(vo);
        }
        return PageDTO.of(page,voList);
    }
}
